package com.district.districtpicker;

import android.content.Context;
import android.content.res.AssetManager;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.district.districtpicker.model.ProvinceModel;
import com.district.districtpicker.model.XmlParserHandler;
import com.district.districtpicker.wheel.OnWheelChangedListener;
import com.district.districtpicker.wheel.WheelView;
import com.district.districtpicker.wheel.adapters.ArrayWheelAdapter;

import java.io.InputStream;
import java.util.HashMap;
import java.util.List;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

/**
 * @author 一叶丶枫凌
 * Created on 2017-06-13 2:01
 */
public class DistrictPicker extends PopupWindow implements OnWheelChangedListener, View.OnClickListener {

    /**
     * 所有省
     */
    private String[] mProvinces;
    /**
     * key - 省 value - 市
     */
    private HashMap<String, String[]> mCitisMap = new HashMap<>();
    /**
     * key - 市 values - 区
     */
    private HashMap<String, String[]> mDistrictMap = new HashMap<>();

    private WheelView mDistrict;
    private WheelView mCity;
    private WheelView mProvince;
    private TextView mYes;
    /**
     * 当前省的名称
     */
    private String mCurrentProvinceName = "";
    /**
     * 当前市的名称
     */
    private String mCurrentCityName = "";
    /**
     * 当前区的名称
     */
    private String mCurrentDistrictName = "";
    private OnCompletedListener mOnCompletedListener;
    private Context mContext;

    public interface OnCompletedListener {

        void onCompleted(String provinceName, String cityName, String districtName);
    }

    public void setOnCompletedListener(OnCompletedListener l) {

        mOnCompletedListener = l;
    }

    public DistrictPicker(Context context) {

        this(context, null);
    }

    public DistrictPicker(Context context, AttributeSet attrs) {

        this(context, attrs, 0);
    }

    public DistrictPicker(Context context, AttributeSet attrs, int defStyle) {

        super(context, attrs, defStyle);
        mContext = context;
        initAreaData();

        // requestWindowFeature(Window.FEATURE_NO_TITLE);
        // setContentView(R.layout.view_sel_area);
        setWidth(LinearLayout.LayoutParams.MATCH_PARENT);
        setHeight(LinearLayout.LayoutParams.WRAP_CONTENT);
        setTouchable(true);
        setOutsideTouchable(true);
        setBackgroundDrawable(mContext.getResources().getDrawable(R.drawable.wheel_bg_shape));

        View view = LayoutInflater.from(mContext).inflate(R.layout.view_sel_area, null);
        setContentView(view);
        mDistrict = (WheelView) view.findViewById(R.id.id_district);
        mCity = (WheelView) view.findViewById(R.id.id_city);
        mProvince = (WheelView) view.findViewById(R.id.id_province);
        mYes = (TextView) view.findViewById(R.id.area_confirm);

        // 添加change事件
        mProvince.addChangingListener(this);
        // 添加change事件
        mCity.addChangingListener(this);
        // 添加change事件
        mDistrict.addChangingListener(this);
        mYes.setOnClickListener(this);

        mProvince.setAdapter(new ArrayWheelAdapter<>(mContext, mProvinces));
        mProvince.setVisibleItems(10);
        mCity.setVisibleItems(10);
        mDistrict.setVisibleItems(10);
        updateCities();
        updateDistrict();
    }

    /**
     * 默认在底部
     */
    public void show() {

        showAtLocation(getContentView(), Gravity.BOTTOM, 0, 0);
    }

    private void initAreaData() {

        List<ProvinceModel> provinceList;
        AssetManager asset = mContext.getAssets();
        try {
            InputStream input = asset.open("province_data.xml");
            // 创建一个解析xml的工厂对象
            SAXParserFactory spf = SAXParserFactory.newInstance();
            // 解析xml
            SAXParser parser = spf.newSAXParser();
            XmlParserHandler handler = new XmlParserHandler();
            parser.parse(input, handler);
            input.close();
            // 获取解析出来的数据
            provinceList = handler.getDataList();
            //*/ 初始化默认选中的省、市、区
            if (provinceList != null && !provinceList.isEmpty()) {
                mCurrentProvinceName = provinceList.get(0).getName();
                List<ProvinceModel.CityModel> cityList = provinceList.get(0).getCityList();
                if (cityList != null && !cityList.isEmpty()) {
                    mCurrentCityName = cityList.get(0).getName();
                    List<ProvinceModel.CityModel.DistrictModel> districtList = cityList.get(0).getDistrictList();
                    mCurrentDistrictName = districtList.get(0).getName();
                }
            }
            mProvinces = new String[provinceList.size()];
            for (int i = 0; i < provinceList.size(); i++) {
                // 遍历所有省的数据
                mProvinces[i] = provinceList.get(i).getName();
                List<ProvinceModel.CityModel> cityList = provinceList.get(i).getCityList();
                String[] cityNames = new String[cityList.size()];
                for (int j = 0; j < cityList.size(); j++) {
                    // 遍历省下面的所有市的数据
                    cityNames[j] = cityList.get(j).getName();
                    List<ProvinceModel.CityModel.DistrictModel> districtList = cityList.get(j).getDistrictList();
                    String[] distrinctNameArray = new String[districtList.size()];
                    ProvinceModel.CityModel.DistrictModel[] distrinctArray = new ProvinceModel.CityModel
                            .DistrictModel[districtList.size()];
                    for (int k = 0; k < districtList.size(); k++) {
                        // 遍历市下面所有区/县的数据
                        ProvinceModel.CityModel.DistrictModel districtModel = new ProvinceModel.CityModel.DistrictModel
                                (districtList.get(k).getName(), districtList.get(k).getZipcode());
                        // 区/县对于的邮编，保存到mZipcodeDatasMap
                        distrinctArray[k] = districtModel;
                        distrinctNameArray[k] = districtModel.getName();
                    }
                    // 市-区/县的数据，保存到mDistrictDatasMap
                    mDistrictMap.put(cityNames[j], distrinctNameArray);
                }
                // 省-市的数据，保存到mCitisDatasMap
                mCitisMap.put(provinceList.get(i).getName(), cityNames);
            }
        } catch (Throwable e) {//
        }
    }

    private void updateCities() {

        int pCurrent = mProvince.getCurrentItem();
        mCurrentProvinceName = mProvinces[pCurrent];
        String[] cities = mCitisMap.get(mCurrentProvinceName);
        if (cities == null) {
            cities = new String[]{};
        }
        mCity.setAdapter(new ArrayWheelAdapter<>(mContext, cities));
        mCity.setCurrentItem(0);
        updateDistrict();
    }

    /**
     * 根据当前的市，更新区WheelView的信息
     */
    private void updateDistrict() {

        int cCurrent = mCity.getCurrentItem();
        mCurrentCityName = mCitisMap.get(mCurrentProvinceName)[cCurrent];
        String[] districts = mDistrictMap.get(mCurrentCityName);

        if (districts == null) {
            districts = new String[]{};
        }
        mDistrict.setAdapter(new ArrayWheelAdapter<>(mContext, districts));
        mDistrict.setCurrentItem(0);
    }

    @Override
    public void onChanged(WheelView wheel, int oldValue, int newValue) {

        if (wheel == mProvince) {
            updateCities();
        } else if (wheel == mCity) {
            updateDistrict();
        } else if (wheel == mDistrict) {
            mCurrentDistrictName = mDistrictMap.get(mCurrentCityName)[newValue];
        }
    }

    @Override
    public void onClick(View v) {
        if (mOnCompletedListener != null) {
            mOnCompletedListener.onCompleted(mCurrentProvinceName, mCurrentCityName, mCurrentDistrictName);
        }
        dismiss();
    }
}